package com.weibo.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class AsyncImageLoader {
	private static final String TAG="AsyncImageLoader";

	private static AsyncImageLoader mImageLoader;
	private HashMap<String, SoftReference<Drawable>> imageCache;
	private BlockingQueue queue ;   
	private ThreadPoolExecutor executor ;
    public static String APPDATAPATH;
    public static String IMAGEDATAPATH;
	  
	     private AsyncImageLoader() {
	    	 imageCache = new HashMap<String, SoftReference<Drawable>>();
	    	 String sDStateString = android.os.Environment.getExternalStorageState();  
	    	 if (sDStateString.equals(android.os.Environment.MEDIA_MOUNTED)) {  
	    		 APPDATAPATH =android.os.Environment   
	                .getExternalStorageDirectory().toString();
	    		 APPDATAPATH =APPDATAPATH+"/"+"140shoot";
	    		   File appdatepath = new File(APPDATAPATH); 
	    		   if(!appdatepath.exists()){
	    			   appdatepath.mkdir();
	    		   }
	    		 IMAGEDATAPATH = APPDATAPATH+"/"+"image";
	    		appdatepath = new File(IMAGEDATAPATH); 
	    		   if(!appdatepath.exists()){
	    			   appdatepath.mkdir();
	    		   }
	    		 Log.e(TAG, "APPDATAPATH= "+APPDATAPATH);
	    		 Log.e(TAG, "APPDATAPATH= "+IMAGEDATAPATH);
	    		 
	    	 }
	    	 
	    	 queue = new LinkedBlockingQueue();
	    	 executor = new ThreadPoolExecutor(1, 50, 180, TimeUnit.SECONDS, queue);
	     }
	     public Drawable loadDrawable(final Context context, final String imageUrl, final ImageCallback imageCallback) {
	    	 return loadDrawable(context,imageUrl,imageCallback,-1);
	     }
	     public Drawable loadDrawable(final Context context, final String imageUrl, final ImageCallback imageCallback,final int what) {
	    	 final String key = MD5.getMD5(imageUrl.getBytes());
	         if (imageCache.containsKey(key)) {
	             SoftReference<Drawable> softReference = imageCache.get(key);
	             Drawable drawable = softReference.get();
	             if (drawable != null) {
	                 return drawable;
	             }
	         }
	         final Handler handler = new Handler() {
	             public void handleMessage(Message message) {
	            	 if(what<0)
	                 imageCallback.imageLoaded((Drawable) message.obj, imageUrl);
	            	 else{
	            		 imageCallback.imageLoaded((Drawable) message.obj, imageUrl,what);
	            	 }
	             }
	         };
	         
	         executor.execute(new Runnable() {
	             public void run() {
	                 Drawable drawable = loadImageFromUrl(context, imageUrl);
	                 Log.e(TAG, "put key ="+key);
	                 imageCache.put(key, new SoftReference<Drawable>(drawable));
	                 Message message = handler.obtainMessage(0, drawable);
	                 handler.sendMessage(message);
	             }
	         });
	         
	         return null;
	     }
	  
		public static Drawable loadImageFromUrl(Context context, String imageUrl) {
			Drawable drawable = null;  
	        if(imageUrl == null )  
	            return null;  
	        String   fileName   = "";  
	              
	        if(imageUrl!=null&&imageUrl.length()!=0){   
	            fileName  = MD5.getMD5(imageUrl.getBytes());  
	        }  
//	        Log.i(TAG,"imagePath = " + imagePath);  
	        File file = new File(IMAGEDATAPATH,fileName);
//	        Log.i(TAG,"file.toString()=" + file.toString());  
	        if(!file.exists()&&!file.isDirectory())  
	        {  
	            try {  
	                  
	                FileOutputStream   fos=new   FileOutputStream( file );  
	                InputStream is = new URL(imageUrl).openStream();  
	                int   data = is.read();   
	                while(data!=-1){   
	                        fos.write(data);   
	                        data=is.read();;   
	                }   
	                fos.close();  
	                is.close();  
//	              drawable = Drawable.createFromStream(  
//	                      new URL(imageUrl).openStream(), file.toString() ); // (InputStream) new URL(imageUrl).getContent();  
	                drawable = Drawable.createFromPath(file.toString());  
	            } catch (IOException e) {  
	                Log.e(TAG, e.toString() + "Load File exception");  
	            }  
	        }else  
	        {  
	            drawable = Drawable.createFromPath(file.toString());  
	        } 
	        return drawable ;
		}
	  
	     public interface ImageCallback {
	         public void imageLoaded(Drawable imageDrawable, String imageUrl);
	         public void imageLoaded(Drawable imageDrawable, String imageUrl,int key);
	     }
	     
	     public HashMap<String, SoftReference<Drawable>> getImageCache(){
	    	 return imageCache;
	     }
	     
	     public static AsyncImageLoader getInstance(){
	    	 if(mImageLoader==null)
	    		 mImageLoader = new AsyncImageLoader();
	    	 return mImageLoader;
	     }
         
}
